package com.example.test.common;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.util.HashSet;
import java.util.Set;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
	private static final Set<String> EXCLUDED_PATHS = new HashSet<>();

	static {
		EXCLUDED_PATHS.add("/user/register");
		EXCLUDED_PATHS.add("/user/login");
		EXCLUDED_PATHS.add("/user/changePassword");
		// swagger 不校验
		EXCLUDED_PATHS.add("/swagger/**");
		EXCLUDED_PATHS.add("/swagger-ui.html/**");
		EXCLUDED_PATHS.add("/swagger-resources/**");
		EXCLUDED_PATHS.add("/webjars/**");
		EXCLUDED_PATHS.add("/csrf");
		EXCLUDED_PATHS.add("/");
		EXCLUDED_PATHS.add("/swagger-ui/index.html");
		EXCLUDED_PATHS.add("/v2/api-docs");
		EXCLUDED_PATHS.add("/favicon.ico");
	}


	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// 动态处理白名单路径
		http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 关闭 Session
				.and()
				.authorizeRequests()
				.antMatchers(EXCLUDED_PATHS.toArray(new String[0])).permitAll() // 通过 EXCLUDED_PATHS 集合来指定白名单接口
				.anyRequest().authenticated() // 其他接口需要认证
				.and().addFilterBefore(new JwtAuthenticationFilter(EXCLUDED_PATHS), UsernamePasswordAuthenticationFilter.class); // 将 EXCLUDED_PATHS 传递给 JwtAuthenticationFilter
	}
}

